package com.example.wyh.intelcheckbash.product_visit;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.bug.BugInfoActivity;
import com.example.wyh.intelcheckbash.bug.BugListRecordActivity;
import com.example.wyh.intelcheckbash.bug.MyRecyclerAdapter;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;
import com.google.zxing.activity.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by chen on 18/1/17.
 */

public class ProductVisitListActivity extends AppCompatActivity {
    public JSONArray mAllProductListData;
    public JSONArray mShowProductList = new JSONArray();
    public RecyclerView mProductListView;
    public MyRecyclerAdapter mProductListAdapter;
    public LinearLayoutManager linearLayoutManager;
    public static int PAGE_NUMBER = 7;
    public static int NEW_PRODUCT_REQUEST_CODE = 1001;
    public int totalPages = 1;

    public boolean isLoading = false;
    public int lastVisibleItem = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_list_activity);
        initActionBar();
//        Log.e("mAllProductListData=============",mAllProductListData.toString());


        mProductListView = (RecyclerView)findViewById(R.id.product_list_view);
        linearLayoutManager = new LinearLayoutManager(this);
        mProductListView.setLayoutManager(linearLayoutManager);
        mProductListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(final RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mProductListAdapter.getItemCount() && !isLoading) {
                    //到达底部之后如果footView的状态不是正在加载的状态,就将 他切换成正在加载的状态
                    if (mAllProductListData.length() - mShowProductList.length() > 0) {
                        isLoading = true;
                        mProductListAdapter.changeState(1);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getData();
                            }
                        }, 2000);
                    } else {
                        mProductListAdapter.changeState(2);
                    }
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //拿到最后一个出现的item的位置
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        });

        showProductInfoInListView();
    }
    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_bug_list,new LinearLayout(ProductVisitListActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }
        ImageView title_logo_id = (ImageView)findViewById(R.id.title_logo_id);
        title_logo_id.setImageResource(R.drawable.check_task);
        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("生产巡视");
        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_bug_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductVisitListActivity.this.finish();
            }
        });
        ImageView right_icon = (ImageView)findViewById(R.id.right_icon);
        right_icon.setImageResource(R.drawable.scan);

        RelativeLayout new_bug_btn = (RelativeLayout)findViewById(R.id.new_bug_btn);
        new_bug_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scanBarcodeOrigion();
            }
        });
    }

    private void getData() {
        Log.e("before===mShowProductList.length()",mShowProductList.length() + ":"+mAllProductListData.length());
        int endShow = mShowProductList.length() + PAGE_NUMBER;
        if (mAllProductListData.length() - mShowProductList.length() < PAGE_NUMBER)
        {
            endShow = mAllProductListData.length();
        }
        int currentShowLength = mShowProductList.length();
        for (int i = currentShowLength; i < endShow; i ++)
        {
            try {
                mShowProductList.put(mAllProductListData.getJSONObject(i));
            }catch (JSONException e)
            {

            }

        }
        Log.e("mShowProductList.length()",mShowProductList.length() + ":"+mAllProductListData.length());

        isLoading = false;
        mProductListAdapter.notifyDataSetChanged();
    }

    public void showProductInfoInListView()
    {
//        mTodayBugList = getBugListData();
        mAllProductListData = getProductListData();
        totalPages = mAllProductListData.length() / PAGE_NUMBER + 1;
        int number = PAGE_NUMBER;
        if (totalPages == 1)
        {
            number = mAllProductListData.length();
        }

        for (int i = 0; i < number; i ++)
        {
            try {
                mShowProductList.put(mAllProductListData.getJSONObject(i));
            }catch (JSONException e)
            {

            }
        }
        lastVisibleItem = mShowProductList.length();
        mProductListAdapter = new MyRecyclerAdapter(ProductVisitListActivity.this,mShowProductList,"ProductVisitListActivity");
        mProductListView.setAdapter(mProductListAdapter);
    }

    public void scanBarcodeOrigion() {
        if (ContextCompat.checkSelfPermission(ProductVisitListActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ProductVisitListActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
        } else {
            startActivityForResult(new Intent(ProductVisitListActivity.this, CaptureActivity.class), 1000);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("requestCode:resultCode",requestCode + ":" +resultCode);

        if (requestCode == 1000) {
            try {
                String scanBarcodeResult = data.getStringExtra(CaptureActivity.SCAN_QRCODE_RESULT);
                if (scanBarcodeResult.length() > 0) {
                    Intent intent = new Intent(ProductVisitListActivity.this, ScanNewPeoductVisitActivity.class);
                    intent.putExtra("scanOrigin",scanBarcodeResult);
                    //跳转到新建生产巡视页面
                    startActivityForResult(intent,NEW_PRODUCT_REQUEST_CODE);
                }
            } catch (Exception e) {

            }
        }
        if (requestCode == NEW_PRODUCT_REQUEST_CODE)
        {
            //新建生产巡视成功之后跳转到列表页请求
            refreshProductListView();
        }else {
            if (resultCode == 1002)
            {
                int position = requestCode - NEW_PRODUCT_REQUEST_CODE - 1;
                try {
                    JSONObject updateData = new JSONObject(data.getStringExtra("uploadData"));
                    mShowProductList.getJSONObject(position).put("isUpload",updateData.getString("isUpload"));
                    mProductListAdapter.notifyDataSetChanged();
                }catch (JSONException e)
                {

                }

            }
        }

    }

    public void refreshProductListView()
    {
        mAllProductListData = getProductListData();
        mShowProductList = new JSONArray();
        totalPages = mAllProductListData.length() / PAGE_NUMBER + 1;
        int number = PAGE_NUMBER;
        if (totalPages == 1)
        {
            number = mAllProductListData.length();
        }

        for (int i = 0; i < number; i ++)
        {
            try {
                mShowProductList.put(mAllProductListData.getJSONObject(i));
            }catch (JSONException e)
            {

            }
        }
        lastVisibleItem = mShowProductList.length();
        mProductListAdapter = new MyRecyclerAdapter(ProductVisitListActivity.this,mShowProductList,"ProductVisitListActivity");
        mProductListView.setAdapter(mProductListAdapter);
//        mBugListAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_CAMERA) {
            scanBarcodeOrigion();
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    public JSONArray getProductListData()
    {
        JSONArray product_list = new JSONArray();
        TaskDbHelper taskDbHelper = new TaskDbHelper(ProductVisitListActivity.this);
        SQLiteDatabase db =  taskDbHelper.getReadableDatabase();
        String query = "user_id = '" + LocalStorage.getUserXtm(ProductVisitListActivity.this)
                + "'";
        String[] columns = {"data","isUpload"};
        Cursor cursor = null;
        try {
            cursor = db.query("product_list", columns, query, null, null, null, null);
            while (cursor.moveToNext()){
                JSONObject task = new  JSONObject();
                if(cursor.getColumnIndex("data")>-1){
                    String data =  cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        task =  new JSONObject(data);
                        task.put("isUpload",cursor.getString(cursor.getColumnIndex("isUpload")));
                    } catch (JSONException e) {

                        e.printStackTrace();
                    }
                }

                product_list.put(task);
            }
        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        //// TODO: 17/12/18 将获取的数据按照时间排序
        product_list = sortWithFindTime(product_list);
        Log.e("product_list",product_list.toString());
        return  product_list;
    }

    public JSONArray sortWithFindTime(JSONArray allData) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d1;
        Date d2;
        JSONObject temp_r = new JSONObject();
        for (int i = 0; i < allData.length() - 1; i++) {
            for (int j = i + 1; j < allData.length(); j++) {
                ParsePosition pos1 = new ParsePosition(0);
                ParsePosition pos2 = new ParsePosition(0);
                try {
                    d1 = sdf.parse(allData.getJSONObject(i).getString("xsqysj"), pos1);
                    d2 = sdf.parse(allData.getJSONObject(j).getString("xsqysj"), pos2);
                    if (d1.before(d2)) {
                        temp_r = allData.getJSONObject(i);
                        allData.put(i, allData.getJSONObject(j));
                        allData.put(j, temp_r);
                    }
                } catch (Exception e) {

                }

            }
        }
        return allData;
    }

    public void jumpToProductInfo(int position)
    {
        JSONObject productInfo = null;
        try {
            productInfo = mShowProductList.getJSONObject(position);
            Intent intent = new Intent(ProductVisitListActivity.this,ProductInfoActivity.class);
            intent.putExtra("productInfo",productInfo.toString());
            startActivityForResult(intent, position + NEW_PRODUCT_REQUEST_CODE + 1);
        }catch (JSONException e)
        {

        }

    }
}
